import Vue from 'vue'
import VueRouter from 'vue-router'
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}
Vue.use(VueRouter)

import Layout from '@/pages/Layout'

const routes=[
  {
    path:'/',
    component:Layout,
    name:'layout',
    redirect:"/home",
    children:[
      {
        path:'/home',
        component:()=>import('@/pages/Home/index'),
        redirect:'/articleList',
        children:[
          {
            path:'/articleList',
            component:()=>import('@/pages/container/ArticleList')
          },
          {
            path:'/articleDetail',
            component:()=>import('@/pages/container/ArticleDetail')
          }
        ]
      },
    ],
  },
  {
    path: '/login',
    component:()=>import('@/pages/Login')
  },
  {
    path: '/register',
    component:()=>import('@/pages/register')
  }
]

const router=new VueRouter({
  routes
})

router.beforeEach(((to, from, next) => {
  let token=localStorage.getItem("token");
  next();
  if(token){
    if(to.path==='/login'||to.path==='/register'){
      console.log("有token去登录页")
      next('/home');
    }else {
      console.log("除login和register的其他页面")
     next();
    }
  }
  else {
    console.log("未登录")
    //未登录
    next();
  }
}))

export default router
